#!/bin/bash

# 设置 CPU 和内存使用率的阈值
CPU_THRESHOLD=90  # CPU 使用率阈值（百分比）
MEM_THRESHOLD=85  # 内存使用率阈值（百分比）

# 获取当前 CPU 使用率
get_cpu_usage() {
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
    echo "$cpu_usage"
}

# 获取当前内存使用率
get_mem_usage() {
    mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
    echo "$mem_usage"
}

# 杀死占用最高的进程
kill_top_process() {
    local resource=$1
    local threshold=$2

    if [ "$resource" == "cpu" ]; then
        # 获取占用 CPU 最高的进程，排除 clangd 和 vscode
        top_process=$(ps -eo pid,comm,%cpu --sort=-%cpu | grep -v 'clangd\|vscode' | head -n 2 | tail -n 1 | awk '{print $1}')
    elif [ "$resource" == "mem" ]; then
        # 获取占用内存最高的进程，排除 clangd 和 vscode
        top_process=$(ps -eo pid,comm,%mem --sort=-%mem | grep -v 'clangd\|vscode' | head -n 2 | tail -n 1 | awk '{print $1}')
    fi

    if [ -n "$top_process" ]; then
        echo "Killing process $top_process due to high $resource usage."
        kill -9 "$top_process"
    else
        echo "No process found with high $resource usage."
    fi
}

# 主循环
while true; do
    cpu_usage=$(get_cpu_usage)
    mem_usage=$(get_mem_usage)

    echo "Current CPU usage: $cpu_usage%"
    echo "Current Memory usage: $mem_usage%"

    #if (( $(echo "$cpu_usage > $CPU_THRESHOLD" | bc -l) )); then
    #    echo "CPU usage exceeds threshold ($CPU_THRESHOLD%)."
    #    kill_top_process cpu $CPU_THRESHOLD
    #fi

    if (( $(echo "$mem_usage > $MEM_THRESHOLD" | bc -l) )); then
        echo "Memory usage exceeds threshold ($MEM_THRESHOLD%)."
        kill_top_process mem $MEM_THRESHOLD
    fi

    sleep 2  # 每 2 秒检查一次
done